<template>
  <div>
    <el-container id="container">
      <el-main>
        <div id="login-box">
          <div class="header">
            {{ system.website_chinese_title }}
            <p>{{ system.website_english_title }}</p>
          </div>
          <div class="main">
            <el-form ref="submitForm" :model="dataForm" :rules="dataRule">
              <el-form-item prop="username">
                <el-input v-model="dataForm.username" :placeholder="i18n('login.username')" class="cuborder-radius" prefix-icon="User" clearable/>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="dataForm.password" type="password" :placeholder="i18n('login.password')" class="cuborder-radius" prefix-icon="Lock" clearable/>
              </el-form-item>

              <el-form-item class="code-item" prop="verification_code">
                <el-input v-model="dataForm.verification_code" :placeholder="i18n('login.verification_code')" class="code-input cuborder-radius" prefix-icon="Key" clearable/>
                <div class="get-code" @click="refreshCode">
                  <VerificationCode :identifyCode="identifyCode"></VerificationCode>
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="login(submitForm)" :loading="loginLoading" class="submit-btn">
                  {{ i18n('common.login') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="copyright" v-html="system.copyright"></div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup name="login">
  import { useBase } from "@/hooks/base/useBase";
  import { useStore } from "@/hooks/store/useStore";
  import { createRandomCode } from "@/utils/library";
  import VerificationCode from "@/components/verification/index";

  const { router, i18n } = useBase()
  const { base, user, menu, system } = useStore()

  const loginLoading = ref(false);
  const submitForm = ref();
  const identifyCode = ref("");
  const identifyCodes = ref("0123456789abcdwerwshdjeJKDHRJHKOOPLMKQ");

  const dataForm = reactive({
    username: "",
    password: "",
    verification_code: ""
  });

  const dataRule = reactive({
    username: [{
      required: true,
      message: i18n("login.rules.username.require"),
      trigger: ["blur", "change"]
    }],
    password: [{
      required: true,
      message: i18n("login.rules.password.require"),
      trigger: ["blur", "change"]
    }],
    verification_code: [{
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error(`${i18n("login.rules.verification_code.require")}`));
        } else if (value.toLowerCase() !== identifyCode.value.toLowerCase()) {
          callback(new Error(`${i18n("login.rules.verification_code.error")}`));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"]
    }],
  });


  onBeforeMount(() => {
    refreshCode();
  });


  onMounted(() => {
    // 监听回车事件
    document.onkeydown = (e) => {
      if (e.keyCode === 13 || loginLoading.value) {
        login(submitForm.value);
      }
    };
  })


  // 登录
  const login = async (form) => {
    if (!form) return;
    form.validate(async (valid, fields) => {
      if (!valid) return;
      loginLoading.value = true;
      try {
        $http({
          url: $http.adornUrl(`/login`),
          method: 'post',
          data: $http.adornData({
            username: dataForm.username,
            password: dataForm.password,
          }),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            // 存储用户的token
            base.setToken(data.data.token)
            user.setUserInfo(data.data.user_info)

            // 清除左侧菜单状态
            menu.setLeftMenuStatus(false)

            router.push({ name: "home" })

          } else {
            $message.error(data.message)
            return
          }
        })
      } finally {
        loginLoading.value = false;
      }
    });
  }


  /**
   * @author zhangxiaofei [<1326336909@qq.com>]
   * @dateTime 2023-02-10
   *
   * 生成随机验证码
   *
   * @return 验证码
   */
  const refreshCode = () => {
    identifyCode.value = "";
    identifyCode.value = createRandomCode(identifyCodes.value, 6);
  }
</script>

<style scoped lang="scss">
  @import "./index.scss";
</style>
